import React, { useContext, useEffect, useState } from "react";
import { MainContext } from "@/src/providers/MainProvider";
import { useTranslation } from "@/src/i18n";
import { MouseProfile } from "@/src/types/types.v1.d";
import { MoreIcon } from "../Icons/MoreIcon";
import {
  Button,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Portal,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import FileSaver from "file-saver";

export default function Configs() {
  const { t } = useTranslation("");

  const {
    profile,
    loadCustomProfile,
    setProfileIndex,
    profileIndex,
    deviceName,
    connectedMouse,
    mouseConfigInfo,
  } = useContext(MainContext);

  const [loadingProfile, setLoadingProfile] = useState(false);

  const [editProfileIndex, setEditProfileIndex] = useState(-1);
  const [editName, setEditName] = useState("");
  const [deleteName, setDeleteName] = useState("");
  const changeProfileNameDlg = useDisclosure();
  const deleteProfileDlg = useDisclosure();

  // 为每个 Menu 组件单独管理打开状态
  const [hoverStates, setHoverStates] = useState(
    profile.profiles.map(() => false)
  );
  const [menuListHoverIndex, setMenuListHoverIndex] = useState(-1); // 新增状态来跟踪 MenuList 的悬停状态

  const [checkMsg, setCheckMsg] = useState("");

  const toast = useToast();

  useEffect(() => {
    profile.setProfiles((profiles: MouseProfile[]) => {
      return profiles.map((profile) => {
        if (
          [
            // "onboardConfig",
            "板载配置",
            "Встроеная конфигурация",
            "Konfiguracja pokładowa.",
            "온보드 구성",
            "オンボード設定",
            "Configuration intégrée",
            "Configuración integrada",
            "Onboard configuration",
            "Onboard-Konfiguration",
          ].includes(profile?.name)
        ) {
          return { ...profile, name: "onboardConfig" };
        }
        return profile;
      });
    });
  }, [t]);

  //  profileIndex 改变时，强制同步 profiles.active
  useEffect(() => {
    profile.setProfiles((prev) =>
      prev.map((p, i) => ({ ...p, active: i === profileIndex }))
    );
    loadCustomProfile(profile.profiles[profileIndex]);
  }, [profileIndex]);

  const changeProfile = async (index: number) => {
    if (profile.profiles.findIndex((profile) => profile.active) === index) {
      return;
    }
    console.log("changeProfile", index);
    try {
      setLoadingProfile(true);
      setProfileIndex(index);
      await profile.activeProfile(index);
      if (connectedMouse) {
        connectedMouse.setBoardConfig({
          currentProfileIndex: index,
          profileCount: profile.profiles.length,
        });
      }
    } catch (error) {
    } finally {
      setLoadingProfile(false);
    }
  };

  const changeProfileName = (index: number) => {
    setEditProfileIndex(index);
    setEditName(profile.profiles[index].name);
    setCheckMsg("");
    changeProfileNameDlg.onOpen();
  };

  const deleteProfile = (index: number) => {
    if (profile.profiles[index].active) {
      toast({
        title: t("noAllowDel"),
        status: "error",
        duration: 2000,
        position: "top",
        containerStyle: {
          marginTop: "60px",
        },
      });
      return;
    } else {
      setEditProfileIndex(index);
      setDeleteName(profile.profiles[index].name);
      deleteProfileDlg.onOpen();
    }
  };

  const exportProfile = (index: number) => {
    const data = profile.profiles[index];
    const exportData = {
      deviceModel: deviceName, // 从 MainContext 中获取
      profileData: data,
    };
    const content = JSON.stringify(exportData);
    const file = new Blob([content], { type: "text/plain;charset=utf-8" });

    FileSaver.saveAs(file, t(data.name) + ".json");
  };

  const importProfile = async (file: File) => {
    try {
      const content = await file.text();
      const importData = JSON.parse(content);

      // 检查导入的配置是否包含设备型号信息
      if (!importData.deviceModel || !importData.profileData) {
        toast({
          title: t("errorType"),
          status: "error",
          duration: 2000,
          isClosable: true,
          position: "top",
          containerStyle: {
            marginTop: "60px",
          },
        });
        return;
      }

      // 检查设备型号是否匹配
      if (importData.deviceModel !== deviceName) {
        toast({
          title: t("notApplicable"),
          status: "error",
          duration: 2000,
          isClosable: true,
          position: "top",
          containerStyle: {
            marginTop: "60px",
          },
        });
        return;
      }

      // 导入配置
      return importData.profileData;
    } catch (error) {
      toast({
        title: t("parsingFailure"),
        status: "error",
        duration: 2000,
        isClosable: true,
        position: "top",
        containerStyle: {
          marginTop: "60px",
        },
      });
      return null;
    }
  };

  const changeProfileNameSubmit = (event: any) => {
    profile.renameProfile(editProfileIndex, editName);
    changeProfileNameDlg.onClose();
    toast({
      title: t("succeededRename"),
      status: "success",
      duration: 2000,
      isClosable: true,
      position: "top",
    });
  };

  const deleteProfileSubmit = async (event: any) => {
    profile.delProfile(editProfileIndex);
    deleteProfileDlg.onClose();

    if (connectedMouse) {
      connectedMouse.setBoardConfig({
        currentProfileIndex: profileIndex,
        profileCount: profile.profiles.length,
      });
    }

    toast({
      title: t("deleteSuccess"),
      status: "success",
      duration: 2000,
      isClosable: true,
      position: "top",
    });
  };

  const checkProfileName = (name: string) => {
    setEditName(name);

    // 检查名称是否已存在（排除当前编辑的配置）
    const nameExists = profile.profiles.some(
      (p, idx) => p.name === name && idx !== editProfileIndex
    );

    if (nameExists) {
      setCheckMsg(t("isHave"));
      return;
    }

    if (name.length < 1 || name.length > 20) {
      setCheckMsg(t("lengthLimit"));
      return;
    }

    setCheckMsg("");
  };

  const handleMouseEnter = (index: number) => {
    const newHoverStates = hoverStates.map((hover, idx) =>
      idx === index ? true : false
    );
    setHoverStates(newHoverStates);
    setMenuListHoverIndex(index); // 确保 MenuList 在鼠标进入时显示
  };

  const handleMouseLeave = () => {
    setHoverStates(profile.profiles.map(() => false));
    setMenuListHoverIndex(-1); // 确保 MenuList 在鼠标离开时隐藏
  };

  const handleMenuListMouseEnter = (index: number) => {
    setMenuListHoverIndex(index); // 确保 MenuList 在鼠标进入时显示
  };

  const handleMenuListMouseLeave = () => {
    setMenuListHoverIndex(-1); // 确保 MenuList 在鼠标离开时隐藏
  };

  return (
    <div className="configs">
      <div className="!border-r-0">
        {profile.profiles.map((profileItem, index) => (
          <div
            key={index}
            className="!px-[24px] hover:!bg-grey-1 flex gap-4 items-center justify-between text-white h-16 aria-selected:border-l-[4px] aria-selected:border-[#0066ff]  aria-selected:bg-[#2b2d31] aria-selected:text-[#0066ff] aria-selected:font-bold"
            aria-selected={profileItem?.active}
          >
            <div
              onClick={() => !loadingProfile && changeProfile(index)}
              className={`flex-1 hover:cursor-pointer text-ellipsis overflow-hidden !w-24 text-sm ${
                loadingProfile ? "opacity-50" : ""
              }`}
            >
              {t(profileItem?.name)}
              {loadingProfile && <span className="ml-2">loading...</span>}
            </div>
            <Menu
              placement="bottom-start"
              isOpen={hoverStates[index] || menuListHoverIndex === index}
            >
              <MenuButton
                onMouseEnter={() => handleMouseEnter(index)}
                onMouseLeave={handleMouseLeave}
              >
                <MoreIcon className="w-5 h-15" />
              </MenuButton>
              <MenuList
                className="white !min-w-20"
                sx={{
                  minW: "120px",
                  transform: "translateX(-67%) translateY(-15px) !important",
                  inset: "auto !important",
                  position: "relative",
                  top: "100%",
                  "&::before": {
                    content: '""',
                    position: "absolute",
                    top: "-6px",
                    right: "10px",
                    width: "0",
                    height: "0",
                    m: "0", // 移除所有边距
                    p: "0", // 移除所有填充
                    borderLeft: "6px solid transparent",
                    borderRight: "6px solid transparent",
                    borderBottom: "6px solid white",
                    filter: "drop-shadow(0 -1px 1px rgba(255,255,255,0.1))",
                  },
                }}
                onMouseEnter={() => handleMenuListMouseEnter(index)} // 新增事件处理程序
                onMouseLeave={handleMenuListMouseLeave} // 新增事件处理程序
              >
                <MenuItem
                  className="text-xs !text-white"
                  isDisabled={index === 0}
                  onClick={() => changeProfileName(index)}
                  sx={{
                    '&[aria-disabled="true"]': {
                      opacity: 0.4,
                      cursor: "not-allowed",
                      _hover: { bg: "transparent" },
                    },
                  }}
                >
                  {t("rename")}
                </MenuItem>
                <MenuItem
                  className="text-xs !text-white"
                  onClick={() => exportProfile(index)}
                >
                  {t("export")}
                </MenuItem>
                <MenuItem
                  className="text-xs !text-white"
                  isDisabled={index === 0}
                  onClick={() => deleteProfile(index)}
                  sx={{
                    '&[aria-disabled="true"]': {
                      opacity: 0.4,
                      cursor: "not-allowed",
                      _hover: { bg: "transparent" },
                    },
                  }}
                >
                  {t("delete")}
                </MenuItem>
              </MenuList>
            </Menu>
          </div>
        ))}
      </div>

      <Portal>
        <Modal
          isOpen={changeProfileNameDlg.isOpen}
          onClose={changeProfileNameDlg.onClose}
          size="lg"
        >
          <ModalOverlay />
          <ModalContent sx={{ color: "white", textAlign: "center" }}>
            <ModalHeader className="text-left">{t("rename")}</ModalHeader>
            <ModalBody>
              <FormControl isInvalid={checkMsg !== ""}>
                <FormLabel>{t("enterConfigName")}</FormLabel>
                <Input
                  value={editName}
                  onChange={(e) => checkProfileName(e.target.value)}
                  placeholder={t("enterConfigName")}
                  minLength={1}
                  maxLength={20}
                />
                <FormErrorMessage color="red.500">{checkMsg}</FormErrorMessage>
              </FormControl>
            </ModalBody>
            <ModalFooter display="flex" justifyContent="center" gap={2}>
              <Button
                className="primary-btn"
                isDisabled={checkMsg !== "" || !editName}
                onClick={changeProfileNameSubmit}
                width="100px"
              >
                {t("ok")}
              </Button>
              <Button
                variant="outline"
                onClick={changeProfileNameDlg.onClose}
                width="100px"
              >
                {t("cancel")}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
        <Modal
          isOpen={deleteProfileDlg.isOpen}
          onClose={deleteProfileDlg.onClose}
          size="lg"
        >
          <ModalOverlay />
          <ModalContent sx={{ color: "white", textAlign: "center" }}>
            <ModalHeader>{t("delConfigFile")}</ModalHeader>
            <ModalBody>
              <p className="text-white-3 text-sm mb-2">
                {t("sureDelPre")}
                <span className="font-bold text-base">{deleteName}</span>
                {t("sureDelAfter")}
              </p>
            </ModalBody>
            <ModalFooter display="flex" justifyContent="center" gap={2}>
              <Button
                colorScheme="red"
                onClick={deleteProfileSubmit}
                width="100px"
              >
                {t("delete")}
              </Button>
              <Button
                variant="outline"
                onClick={deleteProfileDlg.onClose}
                width="100px"
              >
                {t("cancel")}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </Portal>
    </div>
  );
}
